<template>
  <!-- 应收应付 -->
  <div>
    <div class="btn-box" v-if="showBtn">
      <div class="btn_left">
        <el-button type="text" @click="openAdd('')"> 新增 </el-button>
        <el-button type="text" @click="copyOne">复制</el-button>
        <el-button type="text" @click="openTemplate">引用模版</el-button>
        <el-button type="text" @click="conversion">{{
          isIncome ? '收入转支出' : '支出转收入'
        }}</el-button>
        <el-button type="text" @click="splitFee">拆分</el-button>
        <el-button type="text" @click="locked(true)">财务锁定</el-button>
        <el-button type="text" @click="locked(false)">取消锁定</el-button>
        <el-button type="text" @click="deleteData">批量删除</el-button>
      </div>
    </div>
    <div class="statistical-information" v-if="feeSum.length">
      <span class="statistical-title"> 含税金额总计：</span>
      <span
        class="statistical-title"
        style="margin-right: 8px"
        v-for="(item, index) in feeSum"
        :key="index"
        >{{ item.type }}:{{ item.money }}</span
      >
    </div>
    <el-table
      :data="tableData"
      border
      max-height="400px"
      size="small"
      @cell-click="cellClick"
      @selection-change="handleSelectionChange"
      :row-style="selectRowClassName"
    >
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="80"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div class="flex-center">
            {{ scope.$index + 1 }}
            <el-icon v-if="scope.row.feeLock"><Lock /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="类型"
        width="80"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.receivedOrPaid }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="结算单位"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
          >
            <el-select
              v-model="scope.row.customerType"
              filterable
              remote
              reserve-keyword
              placeholder="请选择"
              size="small"
              :remote-method="selectEntOptions"
              :loading="state.customerloading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.customerList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
                @click="getEntOption(item, scope.$index)"
                ><span style="float: left">{{ item.leftName }}</span>
                <span style="float: right">{{ item.rigthName }}</span>
              </el-option>
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.customerType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="费用名称"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
          >
            <el-select
              v-model="scope.row.feeName"
              filterable
              remote
              reserve-keyword
              placeholder="请选择"
              size="small"
              :remote-method="selectFeeOptions"
              :loading="state.feeloading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.feeList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
                @click="getFeeLeverOption(item, scope.$index)"
              >
              </el-option>
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.feeName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="币种"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
          >
            <el-select
              v-model="scope.row.currency"
              filterable
              remote
              placeholder="请选择"
              size="small"
              :remote-method="queryCurrency"
              remote-show-suffix
              :loading="state.currencyLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.currencyList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
                @click="getCurOption(item, scope.$index)"
              >
              </el-option>
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.currency }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="单价"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
            class="input-number-style"
          >
            <el-input-number
              v-model="scope.row.price"
              placeholder="请输入"
              :precision="2"
              :controls="false"
              @change="calulateValue(scope.row)"
            />
          </div>
          <span v-else>
            {{ scope.row.price }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="单位"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
          >
            <el-select
              v-model="scope.row.unit"
              filterable
              remote
              placeholder="请选择"
              size="small"
              :remote-method="queryUnit"
              remote-show-suffix
              :loading="state.unitLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.unitList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.unit }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="数量"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div
            v-if="
              scope.$index === state.rowIndex &&
              scope.column.no === state.columnIndex
            "
          >
            <!-- <el-input
              v-model="scope.row.feeCount"
              size="small"
              placeholder="请输入"
              @input="scope.row.feeCount = validateNumber(scope.row.feeCount)"
            >
            </el-input> -->
            <el-input-number
              v-model="scope.row.feeCount"
              placeholder="请输入"
              :precision="0"
              :min="1"
              @change="calulateValue(scope.row)"
              :controls="false"
            />
          </div>
          <span v-else>
            {{ scope.row.feeCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="实际金额"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.feeAmount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="费用状态"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.feeState == 0 ? '未审核' : '已审核' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="转化汇率"
        width="140"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.exchangeRate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="折本币金额"
        width="140"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.feeAmountRmb }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="税率"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.taxRate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="税金"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.taxAmount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="含税金额"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.amountIsTax }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发票号码"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.invoiceCode }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发票币种"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.invoiceCurrency }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发票类型"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.invoiceType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发票金额"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.invoiceAmount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="已核销金额"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.writtenOff }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="未核销金额"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.notWrittenOff }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="最新核销日期"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{
              scope.row.newWrittenDate
                ? $utils.formatDateTime(scope.row.newWrittenDate, 'YYYY-MM-DD')
                : ''
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="核销结束标记"
        width="120"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>
            {{ scope.row.writtenEnd }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="80" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="openAdd(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <docFeeInformation
      :isIncome="isIncome"
      ref="docFeeInformationRef"
      :showBtn="showBtn"
      @save="addData"
    ></docFeeInformation>
    <docFeeAddTemplate
      :isIncome="isIncome"
      ref="docFeeAddTemplateRef"
      @saveFeeModule="saveFeeModule"
    ></docFeeAddTemplate>
  </div>
</template>

<script setup>
import { defineComponent, reactive, toRaw, ref, watch, computed } from 'vue'
import docFeeInformation from './docFeeInformation.vue'
import docFeeAddTemplate from './docFeeAddTemplate.vue'
import {
  validateOnlyNumberTwo,
  validateNumber,
  validataPhoneAndTelephone
} from '@/utils/validate.js'
import request from '@/public/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore, Store } from 'vuex'

const Router = useRouter()
const Route = useRoute()
const store = useStore()
const emits = defineEmits(['conversion'])

const props = defineProps({
  //详细数据
  tableData: {
    type: Array,
    default: () => []
  },
  //控制编辑和查看
  showBtn: {
    type: Boolean,
    default: false
  },
  //汇总各个币种金额
  feeSum: {
    type: Array,
    default: () => []
  },
  //应收应付
  isIncome: {
    type: Boolean,
    default: false
  }
})

const state = reactive({
  rowIndex: -1,
  columnIndex: -1,
  // 获取币种
  currencyLoading: false,
  currencyList: [],
  // 结算对象
  customerloading: false,
  customerList: [],
  // 费用名称
  feeloading: false,
  feeList: [],
  // 单位
  unitLoading: false,
  unitList: [],
  tableSelect: []
})

function saveFeeModule(data) {
  data.exchangeRate = 1
  data.currency = data.currencyCode
  if (props.isIncome) {
    data.receivedOrPaid = '应收'
  } else {
    data.receivedOrPaid = '应付'
  }
  calulateValue(data)
  props.tableData.push(data)
}

/**
 * 选择后的数据
 */
function handleSelectionChange(val) {
  let arr = []
  for (let item of val) {
    let ret = toRaw(item)
    if (ret !== undefined) {
      arr.push(ret)
    }
  }
  state.tableSelect = arr
}

// 新增
function addData(data, isSave) {
  if (isSave) {
    props.tableData.push(data)
  } else {
  }
}

// 显示操作
function limtOpration() {
  let haslocked = false
  let levelToLow = false
  for (let i = state.tableSelect.length - 1; i >= 0; i--) {
    if (state.tableSelect[i].feeLock) {
      haslocked = true
      break
    }
    if (
      store.state.auth.employee.updateLevel <=
      parseInt(state.tableSelect[i].feeLevel)
    ) {
      levelToLow = true
      break
    }
  }
  if (levelToLow && !haslocked) {
    ElMessage.warning('该条费用信息您无权操作')
  }
  if (haslocked && !levelToLow) {
    ElMessage.warning('当前选择的费用中存在已锁定')
  }
  return levelToLow || haslocked
}

// 复制
function copyOne() {
  if (state.tableSelect.length) {
    if (limtOpration()) {
      return
    }
    for (const iterator of state.tableSelect) {
      let copyData = JSON.parse(JSON.stringify(iterator))
      copyData.id = 0
      props.tableData.push(copyData)
    }
  } else {
    ElMessage.warning('请至少选中一条数据')
  }
}

defineExpose({
  state
})

// 费用锁定
async function locked(locking) {
  if (state.tableSelect.length == 1) {
    console.log(
      store.state.auth.employee.updateLevel,
      parseInt(state.tableSelect[0].feeLevel)
    )
    if (
      store.state.auth.employee.updateLevel <=
      parseInt(state.tableSelect[0].feeLevel)
    ) {
      ElMessage.warning('该条费用信息您无权限操作')
      return
    }

    if (locking) {
      ElMessageBox.confirm(
        '您已进行财务锁定，如需进行编辑，请点击取消锁定',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          let res = await request.post('/api/fefee/feelock', {
            id: state.tableSelect[0].id,
            feeLock: locking
          })
          state.tableSelect[0].feeLock = locking
        })
        .catch(() => {})
    } else {
      let res = await request.post('/api/fefee/feelock', {
        id: state.tableSelect[0].id,
        feeLock: locking
      })
      state.tableSelect[0].feeLock = locking
    }
  } else {
    ElMessage.warning('请选择一条数据')
  }
}

// 查询获取币种
const queryUnit = async (query) => {
  state.unitLoading = true
  let res = await request.get('/api/cscontainer/querypage', {
    ContainerCode: query,
    PageIndex: 1,
    PageSize: 50
  })
  state.unitList = res.content.map((item) => {
    return {
      label: item.containerCode,
      value: item.containerCode
    }
  })
  state.unitList.push({
    label: '票',
    value: '票'
  })
  state.unitLoading = false
}

// 费用拆分 默认拆分成两个
async function splitFee() {
  // 拆分
  if (!state.tableSelect.length) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  if (limtOpration()) {
    return
  }
  for (const item of state.tableSelect) {
    let copyItem = JSON.parse(JSON.stringify(item))
    let feeMount = Math.floor(parseInt(copyItem.feeCount) / 2)
    item.feeCount = feeMount
    copyItem.feeCount = copyItem.feeCount - feeMount
    calulateValue(copyItem)
    calulateValue(item)
    props.tableData.push(copyItem)
  }
}

// 重新根据单价汇率和数量重新计算个值
function calulateValue(row) {
  row.feeAmount =
    (row.feeCount ? parseFloat(row.feeCount) : 1) *
    (row.price ? parseFloat(row.price) : 0)
  row.feeAmountRmb =
    (row.feeAmount ? row.feeAmount : 0) *
    parseFloat(row.exchangeRate ? row.exchangeRate : 1)
  row.taxAmount =
    row.feeAmountRmb * ((row.taxRate ? parseFloat(row.taxRate) : 0) / 100)
  row.amountIsTax =
    row.feeAmountRmb * (1 + (row.taxRate ? parseFloat(row.taxRate) : 0) / 100)
  console.log(row, 'row')
}

// 收入和支出相互转换
function conversion() {
  if (!state.tableSelect.length) {
    ElMessage.warning('请至少选择一条数据')
    return
  }
  if (limtOpration()) {
    return
  }
  let cpoyTableSelect = JSON.parse(JSON.stringify(state.tableSelect))
  deleteData()
  emits('conversion', props.isIncome, cpoyTableSelect)
}
/**
 * 结算对象编码的option
 * @param {object} item - 选择的option
 */
function getEntOption(item, index) {
  props.tableData[index].customerCode = item.leftName
}

/**
 * 费用名称的option
 * @param {object} item - 选择的option
 */
function getFeeLeverOption(item, index) {
  props.tableData[index].feeLevel = item.defaultLevel
}

/**
 * 费用名称的option
 * @param {object} item - 选择的option
 */
async function getCurOption(item, index) {
  let res = await request.get('/api/cscurrencyrate/queryby', {
    currencyCode: item.currencyCode
  })
  if (res.data) {
    props.tableData[index].exchangeRate = res.data.exchangeRate
  } else {
    props.tableData[index].exchangeRate = 1
  }
  calulateValue(props.tableData[index])
}

// 打开输入弹框
function openAdd(row) {
  if (row.feeLock && props.showBtn) {
    ElMessage.warning('该条费用信息已锁定')
    return
  }
  if (
    store.state.auth.employee.updateLevel <= parseInt(row.feeLevel) &&
    props.showBtn
  ) {
    ElMessage.warning('该条费用信息您无权操作')
    return
  }
  docFeeInformationRef.value.open(row)
}

// 高亮勾选行
function selectRowClassName({ row, rowIndex }) {
  if (state.tableSelect.includes(row)) {
    return {
      'background-color': '#5A9CF819'
    }
  }
  return ''
}

const docFeeAddTemplateRef = ref(null)
const docFeeInformationRef = ref(null)

//单元格被点击时会触发该事件
async function cellClick(row, column, cell, event) {
  // if (!props.showBtn) {
  //   return
  // }
  if (column.no != 0 && column.label != '操作') {
    if (
      store.state.auth.employee.updateLevel <= parseInt(row.feeLevel) &&
      props.showBtn
    ) {
      ElMessage.error('该条费用信息您无权限修改')
      return
    }
    if (row.feeLock && props.showBtn) {
      ElMessage.warning('该条费用信息已锁定')
      return
    }
    if (props.showBtn) {
      state.rowIndex = props.tableData.findIndex((t) => t == row)
      state.columnIndex = column.no
    }
  }
}

/**
 * 删除
 */
function deleteData() {
  if (state.tableSelect.length > 0) {
    if (limtOpration()) {
      return
    }
    for (let i = state.tableSelect.length - 1; i >= 0; i--) {
      let deleteIndex = props.tableData.findIndex(
        (t) => t == state.tableSelect[i]
      )
      if (deleteIndex > -1) {
        props.tableData.splice(deleteIndex, 1)
      }
    }
  } else {
    ElMessage.warning('请选择选择数据')
  }
}

// 查询获取币种
const queryCurrency = async (query) => {
  state.currencyLoading = true
  let res = await request.get('/api/cscurrency/querypage', {
    KeyWords: query,
    PageIndex: 1,
    PageSize: 50
  })
  state.currencyList = res.content.map((item) => {
    return {
      label: item.currencyCode,
      value: item.currencyCode
    }
  })
  console.log(res, 'res')
  state.currencyLoading = false
}

/**
 * 查询结算对象编码数据
 * @param {string} query - 输入内容查询
 */
async function selectEntOptions(query) {
  state.customerloading = true
  request
    .get('/api/crcontactcompany/query', {
      code: query,
      PageIndex: 1,
      PageSize: 50,
      businessCategory: ''
    })
    .then((res) => {
      state.customerList = res.content.map((item) => {
        return {
          id: item.id,
          value: item.comNameCn,
          label: item.comNameCn,
          selectLabel: `${item.comCode}|${item.comNameCn}`,
          name: item.comNameCn,
          leftName: item.comCode,
          rigthName: item.comNameCn
        }
      })
    })
    .finally(() => (state.customerloading = false))
}

/**
 * 查询费用名称编码数据
 * @param {string} query - 输入内容查询
 */
async function selectFeeOptions(query) {
  state.feeloading = true
  request
    .get('/api/csfeesname/querypage', {
      KeyWords: query,
      PageIndex: 1,
      PageSize: 50
    })
    .then((res) => {
      res.content.forEach((item) => {
        item.value = item.nameCh
        item.label = item.nameCh
      })
      state.feeList = res.content
    })
    .finally(() => (state.feeloading = false))
}

// 打开模版
function openTemplate() {
  docFeeAddTemplateRef.value.open()
}

function editRowData(row) {
  docFeeInformationRef.value.open()
}
</script>
<style lang="scss" scoped>
@import '@/styles/business/business.scss';
:deep(.el-table) {
  .el-table__header th {
    background-color: #f7f8fa;
  }
  .cell {
    height: 32px;
    line-height: 32px;
  }
  .el-table_1_column_1 .cell {
    display: flex;
    align-items: center;
    height: 100%;
  }
  .el-table__cell {
    padding: 0;
    height: 32px;
  }
  .el-input-number {
    width: 100%;
    .el-input__inner {
      text-align: left;
      padding: 0 8px;
    }
    .el-input-number__decrease {
      display: none;
    }
    .el-input-number__increase {
      display: none;
    }
  }
  .el-input__inner {
    padding: 0 8px;
  }
  .el-date-editor {
    .el-input__prefix {
      display: none;
    }
  }
  .input-number-style {
    :deep(.el-input-number.is-without-controls .el-input__wrapper) {
      padding: 2px 8px;
    }
    :deep(.el-input-number .el-input__inner) {
      text-align: left;
    }
  }
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
